﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Expect.Core;

namespace Expect.VisualStudio.Extensions
{
    static class SpecificationHelpers
    {
        public static FixtureDefinition GetFixtureAtLine(this SpecificationDefinition spec, string linetext, int linenumber)
        {
            FixtureDefinition res = null;

            if (spec.Setup != null)
            {
                res = spec.Setup.GetFixtureAtLine(linetext, linenumber);
                if (res != null) return res;
            }

            foreach (var fixture in spec.Fixtures)
            {
                FixtureRow lastrow = null;
                foreach (var row in fixture.Rows)
                {
                    if (row.MetaData != null && row.MetaData.LineNumber == linenumber)
                    {
                        return fixture;
                    }
                    lastrow = row;
                }
                
                if (lastrow != null && (lastrow.MetaData.LineNumber + 1) == linenumber && string.IsNullOrEmpty(linetext))
                {
                    return fixture;
                }
            }

            foreach (var childSpec in spec.ChildSpecs)
            {
                res = childSpec.GetFixtureAtLine(linetext, linenumber);
                if (res != null) return res;
            }

            if (spec.Teardown != null)
            {
                res = spec.Teardown.GetFixtureAtLine(linetext, linenumber);
                if (res != null) return res;
            }

            return res;
        }

        public static FixtureRow GetRowAtLine(this FixtureDefinition fixture, int linenumber)
        {
            FixtureRow res = null;

            foreach (var row in fixture.Rows)
            {
                if (row.MetaData != null && row.MetaData.LineNumber == linenumber)
                {
                    return row;
                }
            }

            return res;
        }
    }
}
